package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderInfo;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private OrderService orderService;

    //在线体检预约
    @RequestMapping("/submit")
    public Result submit(@RequestBody OrderInfo orderInfo) {
        String telephone = orderInfo.getTelephone();
        //1.从redis中获取保存的验证码
        Jedis resource = jedisPool.getResource();
        String validateCodeInRedis = resource.get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        resource.close();
        String validateCode = orderInfo.getValidateCode();
        //2.将用户输入的验证码和Redis中保存的验证码进行对比
        if (validateCode != null && validateCode.equals(validateCodeInRedis)) {
            //3.如果对比成功,调用服务完成业务处理
            orderInfo.setOrderType(Order.ORDERTYPE_WEIXIN);//设置预约类型,分为微信预约和电话预约
            Result result;
            try {
                //通过dubbo远程调用服务实现在线预约业务处理
                result = orderService.order(orderInfo);
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, MessageConstant.ORDER_FALSE);
            }
            //3.1预约成功,可以为用户发送短信
            if (result.isFlag()) {
                System.out.println("预约成功");
            }
            return result;
        }
        //如果对比不成功,返回结果给页面
        return new Result(false, MessageConstant.VALIDATECODE_ERROR);
    }

    @RequestMapping("/findById")
    public Result findById(Integer id) throws Exception {
        try {
            Map<String, Object> map = orderService.findById4Detail(id);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);

        }

    }
}

